/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.workflow.service.upcoming.complete.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.je.bpm.engine.impl.cmd.SubmitTypeEnum;
import com.je.bpm.engine.impl.identity.Authentication;
import com.je.common.base.DynaBean;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 变更人员-加签
 */

@Service
public class AddUpcomingServiceImpl extends AbstractCompleteUpcomingService {

    @Override
    public void complete(String taskId, String beanId, String comment, String piid, String nodeId, Map<String, String> params, Map<String, Object> bean) {
        List<DynaBean> list = metaService.select("JE_WORKFLOW_RN_TASK", ConditionsWrapper.builder()
                .eq("TASK_PIID", piid).eq("TASK_NODE_ID", nodeId));

        if (list.size() == 0) {
            return;
        }

        List<DynaBean> currentUserTaskList = metaService.select("JE_WORKFLOW_RN_TASK", ConditionsWrapper.builder().
                eq("TASK_ACTIVITI_TASK_ID", taskId));
        if (currentUserTaskList.size() > 0) {
            return;
        }
        DynaBean task = list.get(0);
        String userId = params.get("user");
        String userName = workFlowUserService.getUserNameById(params.get("user"));
        String executionId = task.getStr("JE_WORKFLOW_RN_EXECUTION_ID");
        DynaBean execution = metaService.selectOneByPk("JE_WORKFLOW_RN_EXECUTION", executionId);
        String assigneeJson = execution.getStr("EXECUTION_ASSIGNEE_JSON");
        JSONArray jsonArray = JSONArray.parseArray(assigneeJson);
        for (Object jsonObject : jsonArray) {
            JSONObject object = (JSONObject) jsonObject;
            if (nodeId.equals(object.getString("nodeId"))) {
                if (!object.getString("assignee").contains(userId)) {
                    object.put("assigneeName", object.getString("assigneeName") + "," + userName);
                    object.put("assignee", object.getString("assignee") + "," + userId);
                    execution.setStr("EXECUTION_ASSIGNEE_JSON", jsonArray.toJSONString());
                    metaService.update(execution);
                    break;
                }
            }
        }

        commonService.buildModelCreateInfo(task);
        task.setStr("SY_CREATEUSERID", Authentication.getAuthenticatedUser().getDeptId());
        task.setStr("JE_WORKFLOW_RN_TASK_ID", UUID.randomUUID().toString());
        task.setStr("TASK_ACTIVITI_TASK_ID", taskId);
        task.setStr("TASK_HANDLE", "0");
        task.setStr("TASK_COLLECT_TIME", "");
        task.setStr("TASK_COLLECT", "0");
        task.setStr("TASK_DELAY", "0");
        task.setStr("ASSIGNEE_ID", userId);
        task.setStr("ASSIGNEE_NAME", userName);
        metaService.insert(task);
        //将这已办的任务删除，后续查询待办比较快
        metaService.executeSql(String.format("DELETE FROM JE_WORKFLOW_RN_TASK WHERE ASSIGNEE_ID='%s' and TASK_PIID='%s'" +
                " and TASK_HANDLE='1'", userId, task.getStr("TASK_PIID")));
        String submitUserId = workFlowUserService.getAssociationIdById(execution.getStr("EXECUTION_SUBMIET_USER_ID"));
        String submitUserName = execution.getStr("EXECUTION_SUBMIT_USER_NAME");
        String submitType = SubmitTypeEnum.getNameByType(execution.getStr("EXECUTION_SUBMIT_TYPE"));
        comment = execution.getStr("EXECUTION_LAST_COMMENT");
        String pkValue = execution.getStr("BUSINESS_KEY");
        String funcCode = execution.getStr("FUNC_CODE");
        String nodeName = execution.getStr("TABLE_CODE");
        pushMag(task.getStr("TASK_PDID"), task.getStr("TASK_NODE_ID"), userId,
                submitType, comment, pkValue, funcCode, nodeName, submitUserName, submitUserId, bean);
    }

}
